<template>
  <!-- <div class="mb-4">
    <el-button>Default</el-button>
    <el-button type="primary">Primary</el-button>
    <el-button type="success">Success</el-button>
    <el-button type="info">Info</el-button>
    <el-button type="warning">Warning</el-button>
    <el-button type="danger">Danger</el-button>
  </div> -->
  <el-row class="login-container" justify="center" :align="'middle'">
    <el-card style="max-width: 480px;">
      <template #header>
        <div class="card-header">
          <img :src="imgUrl" alt="">
        </div>
      </template>
      <div class="jump-link">
        <!-- 蓝色链接按钮 -->
        <el-link type="primary" @click="handleChange">
          {{ formType ? '返回登录' : '注册账号' }}
        </el-link>
      </div>
      <!-- 表单：填写信息 -->
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        style="max-width: 600px;"
        class="demo-ruleForm"
        :rules="rules">
        <!-- 用户名输入框 -->
        <el-form-item prop="userName">
          <el-input v-model="loginForm.userName" placeholder="手机号" :prefix-icon="UserFilled"></el-input>
        </el-form-item>
        <!-- 密码输入框 -->
        <el-form-item prop="passWord">
          <el-input v-model="loginForm.passWord" type="password" placeholder="密码" :prefix-icon="Lock"></el-input>
        </el-form-item>
        <el-form-item v-if="formType" prop="validCode">
          <el-input v-model="loginForm.validCode" placeholder="验证码" :prefix-icon="Lock">
            <template #append>
              <span @click="countdownChange">{{ countdown.validText }}</span>
            </template>
          </el-input>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item>
          <el-button type="primary" :style="{ width: '100%' }" @click="submitForm(loginFormRef)">
            {{ formType ? '注册账号' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-row>
</template>
<script setup>
import { ref, reactive, computed, toRaw } from 'vue';
import { getCode, userAuthentication, login, menuPermissions } from '../../api';
import { ElMessage } from 'element-plus';
import { UserFilled, Lock } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';


const imgUrl = new URL('../../../public/login-head.png', import.meta.url).href;

const loginForm = reactive({
  userName : '',
  passWord : '',
  validCode : ''
});

// 切换表单（0登录， 1注册）
const formType = ref(0);

// 点击切换登录和注册
const handleChange = () => {
  formType.value = formType.value ? 0 : 1;
};

// 账号校验规则
const validateUser = (rule, value, callback) => {
  if (value === '') {
    callback(new Error("请输入正确的手机号"));
  }
  else {
    const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
    phoneReg.test(value) ? callback() : callback(new Error("手机号格式不对，请输入正确的手机号"));
  }
};

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error("请输入密码"));
  }
  else {
    const Reg = /^[a-zA-Z0-9_-]{4,16}$/;
    Reg.test(value) ? callback() : callback(new Error("密码格式不对，需要4到16位字符，请确认格式"));
  }
};

// 表单校验
const rules = reactive({
  // 字体校验的时候触发
  userName: [{ validator: validateUser, trigger: 'blur' }],
  passWord: [{ validator: validatePass, trigger: 'blur' }],
});

// 发送短信
// 创建了一个名为 countdown 的响应式对象，包含 validCode 和 time 两个属性。
const countdown = reactive({
  validCode: '获取验证码',
  time: 60
});

// 创建变量判断是否已经开始倒计时
// flag可以防止用户多次连续点击时系统创建多个对象造成的资源浪费
let flag = false;
const countdownChange = () => {
  // 如果已经发送则不处理
  if (flag) {
    return;
  }
  // 判断手机号是否正确
  const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
  if (!loginForm.userName || !phoneReg.test(loginForm.userName)) {
    return ELMessage({
      message: '请检查手机号是否正确',
      type: 'warning'
    });
  }

  const time = setInterval(() => {
    if (countdown.time <= 0) {
      countdown.time = 0;
      countdown.validCode = `获取验证码`;
      flag = false;
      clearInterval(time);
    }
    else {
      countdown.time -= 1;
      countdown.validCode = `剩余${countdown.time}s`;
    }
  }, 1000);
  flag = true;
  getCode({tel: loginForm.userName}).then(({data}) => {
    if (data.code === 10000) {
      ElMessage.success("发送成功");
    }
  });
};

const router = useRouter();

const loginFormRef = ref();

const store = useStore();

const routerList = computed(() => store.state.menu.routerList);

// 表单提交
const submitForm = async (formEl) => {
  if (!formEl) return
  // 手动触发表单校验
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      // 注册界面
      if (formType.value) {
        userAuthentication(loginForm).then(({ data }) => {
          if (data.code === 10000) {
            ELMessage.success('注册成功，请登录');
            formType.value = 0;
          }
        });
      }
      // 登录页面
      else {
        login(loginForm).then(({ data }) => {
          if (data.code === 10000) {
            ELMessage.success('登录成功');
            // 将token和用户信息缓存到浏览器
            localStorage.setItem('pz_token', data.data.token);
            // 用户信息是引用，需要用json先转成字符串
            localStorage.setItem('pz_userInfo', JSON.stringify(data.data.userInfo));
            // 页面跳转
            menuPermissions().then(({ data }) => {
              store.commit('dynamicMenu', data.data);
              toRaw(routerList.value).forEach(item => {
                router.addRoute('main', item);
              });
              router.push('/');
            });
          }
        });
      }
    } else {
      console.log('error submit!', fields)
    }
  })
};
</script>

<style lang="less" scoped>
  :deep(.el-card__header) {
    padding: 0
  }
  .login-container {
    height: 100%;
    .card-header{
      background-color: #899fe1;
      img {
        width: 430px;
      }
    }
    .jump-link {
      text-align: right;
      margin-bottom: 10px;
    }
  }
</style>